import { useTtsaStore } from '@/store/ttsa'
// import { useBusinessConfig } from '@/hooks'
import { useTost } from '@/utils/comps'
import Clipboard from 'clipboard'
import { useUserStore } from '@/store/user'


export default function useCopyClick() {

  const clipboardSuccess = (message = '已复制') => useTost(message)

  const clipboardError = (message = '复制失败') => useTost(message)

  /**
   * 复制事件
   * @param text 文字
   * @param event 需要绑定的元素
   */
  const useCopy = (
    text: string,
    event: Event | LooseObject,
    customOnSuccess?: boolean | LooseFunction,
    customOnError?: boolean | LooseFunction
    ) => {
      return new Promise((resolve, reject) => {
        event = event || {}
        const clipboard: LooseObject = new Clipboard(event.target, {
          text: () => text,
        })
        clipboard.on('success', () => {
          if (customOnSuccess) {
            typeof customOnSuccess === 'function' && customOnSuccess()
          } else {
            clipboardSuccess()
          }
          clipboard.off('error')
          clipboard.off('success')
          clipboard.destroy()
          resolve(text)
        })
        clipboard.on('error', () => {
          if (customOnError) {
            typeof customOnError === 'function' && customOnError()
          } else {
            clipboardError()
          }
          clipboard.off('error')
          clipboard.off('success')
          clipboard.destroy()
          reject()
        })
        clipboard.onClick(event)
      })
  }

  /**
   * 绑定双击事件
   * @param el 需要绑定的元素
   * @param handler 处理事件
   */
  const useDBClick = (el: Element | Window, handler: LooseFunction) => {
    let prevClickTimes: number
    try {
      el?.addEventListener?.('touchend', (event: Event) => {
        if (!prevClickTimes) {
          prevClickTimes = Date.now()
          return
        }
        if (Date.now() - prevClickTimes < 250) {
          handler?.(event)
        }
        prevClickTimes = null
      })
    } catch {
      // ignore...
    }
  }

  /**
   * 通过给指定元素绑定双击事件，将当前数字人链接信息复制到黏贴板
   * @param el 需要绑定的元素
   * @param handler 处理事件
   */
  const useClipboardLocal = (el: Element | Window, handler?: LooseFunction) => {
    if (el) {
      useDBClick(el, (event: Event) => {
        const ttsaStore = useTtsaStore()
        try {
          const text = JSON.stringify({
            vhop: {
              ...ttsaStore.ttsa.recoveryRoom.state,
            },
            business: {
              ...useUserStore(),
              href: location.href,
            },
            t: new Date().toLocaleString(),
          })
          useCopy(
            text,
            event,
            () => {
              handler?.()
            },
            true,
          )
        } catch {
          // ignore...
        }
      })
    }
  }


  return {
    useClipboardLocal,
    useCopy
  }
}